from django.contrib.auth.models import Permission, Group
from django.contrib.contenttypes.models import ContentType
from django.db import transaction
from rest_framework import serializers
from users.models import User


class PermissionPermsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Permission
        fields = '__all__'
        extra_kwargs = {
            'id': {'read_only': True}
        }


class PermissionContenttypesSerializer(serializers.ModelSerializer):
    class Meta:
        model = ContentType
        fields = ('id', 'name')


class PermissionGroupsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Group
        fields = '__all__'
        extra_kwargs = {
            'id': {'read_only': True}
        }


class PermissionSimpleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Permission
        fields = ('id', 'name')


class PermissionAdminsSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'email', 'mobile',
                  'groups', 'user_permissions', 'password')
        extra_kwargs = {
            'id': {'read_only': True},
            'password': {'write_only': True,
                         'required': False,
                         'allow_blank': True}
        }

    def create(self, validated_data):
        validated_data['is_staff'] = True
        user = super().create(validated_data)
        password = user.password
        if not password:
            password = '123456789'
        user.set_password(password)
        user.save()
        return user

    def update(self, instance, validated_data):
        password = validated_data.pop('password', None)
        super().update(instance, validated_data)
        if password:
            instance.set_password(password)
            instance.save()
        return instance


class PermissionGroupsSimpleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Group
        fields = ('id', 'name')
